<template>
  <section class="container">
    <FormItem
      :form-items="formItem"
      @enter-key="handleQuery"
      @button-click="handleButtonClick"
    />
    <Table
      @handleClick="handleClick"
      @handleChange="handleChange"
      :total="total"
      :columns="tableColumns"
      :data="data"
    />
    <Dialog
      :model-value="dialogVisible"
      :title="dialogTitle"
      :form-fields="formFields"
      :current-data="currentRowData"
      @update:model-value="dialogVisible = $event"
      @submit="handleFormSubmit"
    />
  </section>
</template>

<script lang="ts" setup>
import FormItem from "~/components/FormItem.vue";
import Table from "~/components/Table.vue";
import { news as formdata, newsColumns as tableColumns } from "./data";
import { list, remove, save, edit } from "../api/news";
import { showNotification } from "~/services/notificationService";
import { ElMessage, ElMessageBox } from "element-plus";
const options = ref<any[]>([]); // 投放渠道

const formItem = ref<any>([]); // 表单
const data = ref<any>([]); // 表格数据
const total = ref<any>(null);
const fetchData = async (v: any = {}) => {
  console.log(v);
  try {
    const response = await list(v); // 替换为你的 API 地址
    console.log(response);
    data.value = response.data.data;
    total.value = response.data.total;
  } catch (error) {
    console.error("Failed to fetch data:", error);
  }
};
onMounted(async () => {
  formItem.value = formdata(options); // 表单
  await fetchData(); // 调用数据请求方法
});

const disabeldForm = () => {
  formFields[0].props.disabled = true;
  formFields[1].props.disabled = true;
};

const undisabledForm = () => {
  formFields[0].props.disabled = false;
  formFields[1].props.disabled = false;
};

const handleClick = async (btn: string, row: any) => {
  console.log(1111, btn, row);
  switch (btn) {
    case "查看":
      dialogTitle.value = "查看新闻";
      disabeldForm();
      openDialog(row); // 打开对话框
      break;
    case "编辑":
      // 处理编辑操作
      dialogTitle.value = "编辑新闻";
      undisabledForm();
      openDialog(row); // 打开对话框
      break;
    case "删除":
      // 处理删除操作

      ElMessageBox.confirm("是否删除该条数据？", "警告", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
        center: true,
      })
        .then(async () => {
          const res = await remove({ _id: row._id });
          if (res.code === 200) {
            showNotification("删除成功", "success");
            // 删除成功，刷新数据
            await fetchData();
          } else {
            showNotification(res.msg, "error");
            // 删除失败，显示错误信息
          }
        })
        .catch(() => {
          ElMessage({
            type: "info",
            message: "已取消删除",
          });
        });

      break;
    default:
      break;
  }
};

const handleChange = async (v: any) => {
  await fetchData({ pageIndex: v }); // 调用数据请求方法
};

const dialogVisible = ref(false);
const dialogTitle = ref("添加新闻");
const formFields = [
  {
    name: "title_cn",
    label: "新闻标题",
    type: "input",
    props: { placeholder: "请输入", disabled: false },
  },
  {
    name: "pageViews",
    label: "浏览量",
    type: "input",
    props: { placeholder: "请输入", disabled: false },
  },
  {
    name: "desc",
    label: "新闻内容",
    type: "textarea",
    props: { placeholder: "请输入内容, 段落以句号(。)结尾", rows: 10, disabled: false },
  },
];
const currentRowData = ref<any>(null);
const openDialog = (rowData: any) => {
  dialogVisible.value = true;
  currentRowData.value = rowData; // 保存当前行的数据
};

const handleFormSubmit = async (formData: any) => {
  if (typeof window !== "undefined") {
    const local = JSON.parse(localStorage.getItem("authUser") || "{}");
    console.log(local);
    let para = {
      ...formData,
      updateUser: local.username,
    };
        console.log("参数",para)

    switch (dialogTitle.value) {
      case "添加新闻":
        delete para._id;
        para.createUser = local.username;
        const res = await save(para); // 调用添加新闻的 API
        if (res.code === 200) {
          showNotification("添加成功", "success");
          // 删除成功，刷新数据
          await fetchData();
        } else {
          showNotification(res.msg, "error");
          // 删除失败，显示错误信息
        }
        break;
      case "编辑新闻":
        const result = await edit(para); // 调用编辑新闻的 API
        if (result.code === 200) {
          showNotification("编辑成功", "success");
          // 删除成功，刷新数据
          await fetchData();
        } else {
          showNotification(result.msg, "error");
          // 删除失败，显示错误信息
        }
        break;
      default:
        break;
    }
  }
};
const handleQuery = async (params: any) => {
  await fetchData(params); // 调用数据请求方法
};
const handleButtonClick = async (type: string, params: any, formEL?: any) => {
  switch (type) {
    case "搜索":
      await fetchData(params); // 调用数据请求方法
      break;
    case "添加":
      dialogTitle.value = "添加新闻";
      undisabledForm();
      openDialog(null);
      break;
    case "重置":
      formEL.resetFields()
      break;
  }
};
</script>

<style scoped lang="stylus">
.container{
  padding 20px
}
</style>
